package com.shaohai.live.ui;

import android.content.Intent;
import android.os.AsyncTask;

import com.google.gson.Gson;
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog;
import com.shaohai.live.LoginActivity;
import com.shaohai.live.entity.ApiPostTaskParams;
import com.shaohai.live.utils.AppDefine;
import com.shaohai.live.utils.RuntimeCfg;
import com.shaohai.live.utils.StringUtils;

import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public abstract class FSQueryBarActivity extends FSBarActivity {
    OkHttpClient client = new OkHttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).build();
    protected Gson gson = new Gson();

    protected abstract void refreshRequestData();

    protected abstract void onRequestDataTaskSuccess(String jsonDatastr);

    protected void refreshRequestDataAsync(ApiPostTaskParams taskParams) {
        new RequestDataAsyncTask(FSQueryBarActivity.this).execute(taskParams);
    }

    protected void redirectLogin() {
        Intent intent = new Intent(context, LoginActivity.class);
        startActivity(intent);
    }

    /**
     * 错误返回ERROR
     */
    protected static class RequestDataAsyncTask extends AsyncTask<ApiPostTaskParams, Void, String> {
        private WeakReference<FSQueryBarActivity> reference;

        public RequestDataAsyncTask(FSQueryBarActivity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            FSQueryBarActivity activity = reference.get();
            activity.showProgressDialog();
        }

        @Override
        protected String doInBackground(ApiPostTaskParams... apiPostParams) {
            FSQueryBarActivity reference = this.reference.get();
            ApiPostTaskParams taskParams = apiPostParams[0];
            String token = StringUtils.isNullOrEmpty(RuntimeCfg.token) ? "" : RuntimeCfg.token;
            RequestBody body = RequestBody.create(AppDefine.JSON, taskParams.getJsonString());
            Request request = new Request.Builder().url(taskParams.url).post(body).addHeader("token", token).build();
            try (Response response = reference.client.newCall(request).execute()) {
                return response.body().string();
            } catch (IOException ie) {
                return "ERROR".concat(ie.getMessage() + "");
            }
        }

        @Override
        protected void onPostExecute(String jstr) {
            super.onPostExecute(jstr);
            FSQueryBarActivity activity = reference.get();
            activity.dismissProgressDialog();
            activity.onRequestDataTaskSuccess(jstr);
        }
    }
}
